from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QTableWidget, QHeaderView, QTabWidget,
    QToolBar, QLabel, QSplitter, QTextEdit
)
from PyQt6.QtGui import QIcon, QAction
from PyQt6.QtCore import Qt
from core.schema_tool import SchemaManager
from utils.logger import get_logger

logger = get_logger(__name__)

class SchemaView(QWidget):
    def __init__(self, table_info=None, parent=None):
        super().__init__(parent)
        self.table_info = table_info
        self.schema_manager = None

        # 创建布局
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # 创建工具栏
        self.create_toolbar()
        layout.addWidget(self.toolbar)

        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Vertical)
        layout.addWidget(splitter)

        # 表结构设计器
        self.designer_table = QTableWidget()
        self.designer_table.setColumnCount(6)
        self.designer_table.setHorizontalHeaderLabels(["列名", "数据类型", "长度", "主键", "非空", "默认值"])
        self.designer_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
        self.designer_table.horizontalHeader().setStretchLastSection(True)
        splitter.addWidget(self.designer_table)

        # SQL预览
        self.sql_preview = QTextEdit()
        self.sql_preview.setReadOnly(True)
        splitter.addWidget(self.sql_preview)

        splitter.setSizes([400, 200])

        # 状态标签
        self.status_label = QLabel("就绪")
        layout.addWidget(self.status_label)

        # 如果提供了表信息，加载表结构
        if table_info:
            self.load_table_structure()

    def create_toolbar(self):
        """创建表设计工具栏"""
        self.toolbar = QToolBar("表设计工具栏")
        self.toolbar.setIconSize(QSize(20, 20))

        # 保存按钮
        self.save_action = QAction(QIcon("resources/icons/save.png"), "保存更改", self)
        self.save_action.triggered.connect(self.save_changes)
        self.toolbar.addAction(self.save_action)

        # 新增列按钮
        self.add_column_action = QAction(QIcon("resources/icons/add_column.png"), "新增列", self)
        self.add_column_action.triggered.connect(self.add_column)
        self.toolbar.addAction(self.add_column_action)

        # 删除列按钮
        self.delete_column_action = QAction(QIcon("resources/icons/delete_column.png"), "删除列", self)
        self.delete_column_action.triggered.connect(self.delete_column)
        self.toolbar.addAction(self.delete_column_action)

        self.toolbar.addSeparator()

        # 生成SQL按钮
        self.generate_sql_action = QAction(QIcon("resources/icons/generate_sql.png"), "生成SQL", self)
        self.generate_sql_action.triggered.connect(self.generate_sql)
        self.toolbar.addAction(self.generate_sql_action)

        # 刷新按钮
        self.refresh_action = QAction(QIcon("resources/icons/refresh.png"), "刷新", self)
        self.refresh_action.triggered.connect(self.refresh)
        self.toolbar.addAction(self.refresh_action)

    def set_table_info(self, table_info):
        """设置表信息并加载结构"""
        self.table_info = table_info
        self.load_table_structure()

    def load_table_structure(self):
        """加载表结构"""
        if not self.table_info:
            self.status_label.setText("错误：未提供表信息")
            return

        try:
            # 初始化Schema管理器
            self.schema_manager = SchemaManager(self.table_info["connection"])

            # 获取表结构
            schema = self.schema_manager.get_table_schema(self.table_info["name"])

            if not schema:
                self.status_label.setText(f"无法获取表结构: {self.table_info['name']}")
                return

            # 清空表格
            self.designer_table.setRowCount(0)

            # 设置行数
            self.designer_table.setRowCount(len(schema["columns"]))

            # 填充数据
            for row_idx, col in enumerate(schema["columns"]):
                # 列名
                self.designer_table.setItem(row_idx, 0, QTableWidgetItem(col["name"]))

                # 数据类型
                self.designer_table.setItem(row_idx, 1, QTableWidgetItem(col["type"]))

                # 长度
                self.designer_table.setItem(row_idx, 2, QTableWidgetItem(str(col.get("length", ""))))

                # 主键
                pk_item = QTableWidgetItem()
                pk_item.setCheckState(Qt.CheckState.Checked if col.get("is_primary", False) else Qt.CheckState.Unchecked)
                pk_item.setFlags(pk_item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
                pk_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.designer_table.setItem(row_idx, 3, pk_item)

                # 非空
                not_null_item = QTableWidgetItem()
                not_null_item.setCheckState(Qt.CheckState.Checked if col.get("not_null", False) else Qt.CheckState.Unchecked)
                not_null_item.setFlags(not_null_item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
                not_null_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.designer_table.setItem(row_idx, 4, not_null_item)

                # 默认值
                self.designer_table.setItem(row_idx, 5, QTableWidgetItem(col.get("default", "")))

            self.status_label.setText(f"已加载表结构: {self.table_info['name']}")
        except Exception as e:
            self.status_label.setText(f"加载表结构错误: {str(e)}")
            logger.error(f"加载表结构错误: {str(e)}")

    def add_column(self):
        """添加新列"""
        row_count = self.designer_table.rowCount()
        self.designer_table.insertRow(row_count)

        # 设置默认值
        self.designer_table.setItem(row_count, 0, QTableWidgetItem("new_column"))
        self.designer_table.setItem(row_count, 1, QTableWidgetItem("varchar"))
        self.designer_table.setItem(row_count, 2, QTableWidgetItem("255"))

        # 主键
        pk_item = QTableWidgetItem()
        pk_item.setCheckState(Qt.CheckState.Unchecked)
        pk_item.setFlags(pk_item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
        pk_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.designer_table.setItem(row_count, 3, pk_item)

        # 非空
        not_null_item = QTableWidgetItem()
        not_null_item.setCheckState(Qt.CheckState.Checked)
        not_null_item.setFlags(not_null_item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
        not_null_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.designer_table.setItem(row_count, 4, not_null_item)

        # 默认值
        self.designer_table.setItem(row_count, 5, QTableWidgetItem(""))

    def delete_column(self):
        """删除选中的列"""
        selected_rows = set()
        for item in self.designer_table.selectedItems():
            selected_rows.add(item.row())

        # 从后往前删除
        for row in sorted(selected_rows, reverse=True):
            self.designer_table.removeRow(row)

    def generate_sql(self):
        """生成SQL语句"""
        if not self.table_info:
            self.sql_preview.setText("无法生成SQL: 未选择表")
            return

        sql = f"ALTER TABLE {self.table_info['name']}\n"

        changes = []
        for row in range(self.designer_table.rowCount()):
            col_name = self.designer_table.item(row, 0).text()
            col_type = self.designer_table.item(row, 1).text()
            col_length = self.designer_table.item(row, 2).text()
            is_pk = self.designer_table.item(row, 3).checkState() == Qt.CheckState.Checked
            not_null = self.designer_table.item(row, 4).checkState() == Qt.CheckState.Checked
            default = self.designer_table.item(row, 5).text()

            # 构建类型
            type_str = col_type
            if col_length and col_type.lower() in ["varchar", "char"]:
                type_str += f"({col_length})"

            # 构建列定义
            col_def = f"{col_name} {type_str}"

            if not_null:
                col_def += " NOT NULL"

            if default:
                # 处理函数默认值
                if default.upper() in ["CURRENT_TIMESTAMP", "NOW()"]:
                    col_def += f" DEFAULT {default}"
                else:
                    col_def += f" DEFAULT '{default}'"

            if is_pk:
                col_def += " PRIMARY KEY"

            changes.append(f"MODIFY COLUMN {col_def}")

        sql += ",\n".join(changes) + ";"
        self.sql_preview.setText(sql)
        self.status_label.setText("已生成SQL语句")

    def save_changes(self):
        """保存更改到数据库"""
        sql = self.sql_preview.toPlainText()
        if not sql:
            self.status_label.setText("错误: 没有要执行的SQL语句")
            return

        if not self.schema_manager:
            self.status_label.setText("错误: Schema管理器未初始化")
            return

        try:
            # 执行SQL
            self.schema_manager.execute_sql(sql)
            self.status_label.setText("更改已成功保存到数据库")
        except Exception as e:
            self.status_label.setText(f"保存更改错误: {str(e)}")
            logger.error(f"保存更改错误: {str(e)}")

    def refresh(self):
        """刷新表结构"""
        if self.table_info:
            self.load_table_structure()